package com.ruoyi.ldzlsb.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.ldzlsb.domain.SbEquipment;
import com.ruoyi.ldzlsb.domain.vo.SbEquipmentVo;
import com.ruoyi.ldzlsb.service.ISbEquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 设备台账控制器
 */
@RestController
@RequestMapping("/sb/equipment")
public class SbEquipmentController extends BaseController {

    @Autowired
    private ISbEquipmentService equipmentService;

    /**
     * 查询设备台账列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbEquipmentVo sbEquipmentVo) {
        startPage();
        List<SbEquipmentVo> list = equipmentService.selectSbEquipmentList(sbEquipmentVo);
        return getDataTable(list);
    }

    /**
     * 获取设备台账详细信息
     */
    @GetMapping(value = "/{equipmentId}")
    public AjaxResult getInfo(@PathVariable("equipmentId") Long equipmentId) {
        try {
            logger.info("获取设备详情: ID={}", equipmentId);
            SbEquipmentVo equipment = equipmentService.selectSbEquipmentByEquipmentId(equipmentId);
            if (equipment != null) {
                logger.info("设备详情获取成功: {}", equipment.getEquipmentName());
            } else {
                logger.warn("未找到指定设备: ID={}", equipmentId);
            }
            return success(equipment);
        } catch (Exception e) {
            logger.error("获取设备详情失败", e);
            return error("获取设备详情失败: " + e.getMessage());
        }
    }

    /**
     * 新增设备台账
     */
    @Log(title = "设备台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbEquipmentVo sbEquipment) {
        try {
        return toAjax(equipmentService.insertSbEquipment(sbEquipment));
        } catch (Exception e) {
            logger.error("新增设备台账失败", e);
            return error(e.getMessage());
        }
    }

    /**
     * 修改设备台账
     */
    @Log(title = "设备台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbEquipmentVo sbEquipment) {
        try {
        return toAjax(equipmentService.updateSbEquipment(sbEquipment));
        } catch (Exception e) {
            logger.error("修改设备台账失败", e);
            return error(e.getMessage());
        }
    }

    /**
     * 删除设备台账
     */
    @Log(title = "设备台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{equipmentIds}")
    public AjaxResult remove(@PathVariable Long[] equipmentIds) {
        return toAjax(equipmentService.deleteSbEquipmentByIds(equipmentIds));
    }
    
    /**
     * 获取设备状态统计
     */
    @GetMapping("/status/stats")
    public AjaxResult getStatusStats() {
        Map<String, Object> stats = equipmentService.getStatusStats();
        return success(stats);
    }
    
    /**
     * 生成设备编码
     */
    @GetMapping("/generate/code/{type}")
    public AjaxResult generateEquipmentCode(@PathVariable("type") String type) {
        try {
            logger.info("开始生成设备编码，类型编码: {}", type);
            
            if (type == null || type.trim().isEmpty()) {
                logger.warn("类型编码为空，使用默认值");
                type = "SB";
            }
            
            // 处理可能的URL编码问题
            if (type.contains("%")) {
                try {
                    type = java.net.URLDecoder.decode(type, "UTF-8");
                    logger.info("URL解码后的类型编码: {}", type);
                } catch (Exception e) {
                    logger.error("URL解码失败", e);
                }
            }
            
            // 如果是"EQ"或"eq"，则使用硬编码值
            if ("EQ".equalsIgnoreCase(type)) {
                String hardcodedCode = "EQ-" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "-" + String.format("%03d", new Random().nextInt(1000));
                logger.info("使用硬编码生成设备编码: {}", hardcodedCode);
                return success(hardcodedCode);
            }
            
        String code = equipmentService.generateEquipmentCode(type);
            logger.info("成功生成设备编码: {}", code);
        return success(code);
        } catch (Exception e) {
            logger.error("生成设备编码失败", e);
            // 即使出错，也返回一个可用的编码
            String fallbackCode = type.toUpperCase() + "-" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "-" + String.format("%03d", new Random().nextInt(1000));
            logger.info("生成设备编码失败，返回备用编码: {}", fallbackCode);
            return success(fallbackCode);
        }
    }
    
    /**
     * 更新设备状态
     */
    @Log(title = "设备状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody Map<String, Object> params) {
        Long equipmentId = Long.valueOf(params.get("equipmentId").toString());
        String status = params.get("status").toString();
        String reason = params.get("reason") != null ? params.get("reason").toString() : "";
        return toAjax(equipmentService.updateStatus(equipmentId, status, reason));
    }
    
    /**
     * 获取设备点检记录
     */
    @GetMapping("/{equipmentId}/inspection/records")
    public AjaxResult getInspectionRecords(
            @PathVariable("equipmentId") Long equipmentId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            startPage();
            List<Map<String, Object>> records = equipmentService.getInspectionRecords(equipmentId);
            return success(records);
        } catch (Exception e) {
            return error("获取设备点检记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备保养记录
     */
    @GetMapping("/{equipmentId}/maintenance/records")
    public AjaxResult getMaintenanceRecords(
            @PathVariable("equipmentId") Long equipmentId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            startPage();
            List<Map<String, Object>> records = equipmentService.getMaintenanceRecords(equipmentId);
            return success(records);
        } catch (Exception e) {
            return error("获取设备保养记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备维修记录
     */
    @GetMapping("/{equipmentId}/repair/records")
    public AjaxResult getRepairRecords(
            @PathVariable("equipmentId") Long equipmentId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            startPage();
            List<Map<String, Object>> records = equipmentService.getRepairRecords(equipmentId);
            return success(records);
        } catch (Exception e) {
            return error("获取设备维修记录失败: " + e.getMessage());
        }
    }

    /**
     * 检查设备编码是否存在（排除自身）
     */
    @GetMapping("/checkCodeExcludeSelf")
    public AjaxResult checkEquipmentCodeExcludeSelf(
            @RequestParam("equipmentCode") String equipmentCode,
            @RequestParam("equipmentId") Long equipmentId) {
        try {
            logger.info("检查设备编码是否存在(排除自身): 编码={}, ID={}", equipmentCode, equipmentId);
            int count = equipmentService.checkEquipmentCodeExistsExcludeSelf(equipmentCode, equipmentId);
            boolean exists = count > 0;
            logger.info("检查结果: 是否存在={}", exists);
            // 返回结果时使用布尔值
            return AjaxResult.success("检查完成", exists);
        } catch (Exception e) {
            logger.error("检查设备编码失败", e);
            return AjaxResult.error("检查失败：" + e.getMessage());
        }
    }

    /**
     * 检查设备编码是否存在
     */
    @GetMapping("/checkCode")
    public AjaxResult checkEquipmentCode(@RequestParam("equipmentCode") String equipmentCode) {
        try {
            logger.info("检查设备编码是否存在: 编码={}", equipmentCode);
            int count = equipmentService.checkEquipmentCodeExists(equipmentCode);
            boolean exists = count > 0;
            logger.info("检查结果: 是否存在={}", exists);
            return AjaxResult.success(exists);
        } catch (Exception e) {
            logger.error("检查设备编码失败", e);
            return AjaxResult.error("检查失败：" + e.getMessage());
        }
    }

    /**
     * 根据设备类型获取可用设备列表
     */
    @GetMapping("/list/byType")
    public AjaxResult getEquipmentsByType(@RequestParam(value = "typeId", required = false) Long typeId) {
        try {
            logger.info("根据类型获取设备列表: typeId={}", typeId);
            SbEquipmentVo query = new SbEquipmentVo();
            
            // 记录所有查询参数，便于调试
            StringBuilder logMsg = new StringBuilder();
            logMsg.append("查询参数: ");
            
            // 如果提供了typeId，按类型筛选
            if (typeId != null) {
                logger.info("使用equipmentTypeId={}作为查询条件", typeId);
                query.setEquipmentTypeId(typeId);
                logMsg.append("equipmentTypeId=").append(typeId);
            } else {
                logger.warn("没有提供typeId参数，将返回所有可用设备");
                logMsg.append("未提供typeId");
            }
            
            // 只获取正常状态的设备
            query.setEquipmentStatus("0"); // 假设0表示空闲状态
            logMsg.append(", equipmentStatus=0");
            
            logger.info(logMsg.toString());
            
            // 调试当前的typeId在数据库中是否有对应的设备
            if (typeId != null) {
                int countByType = equipmentService.countEquipmentByTypeId(typeId);
                logger.info("数据库中设备类型ID={}的设备总数: {}", typeId, countByType);
            }
            
            List<SbEquipmentVo> equipments = equipmentService.selectSbEquipmentList(query);
            logger.info("查询到{}台设备", equipments.size());
            
            // 记录设备详情以便调试
            if (equipments.isEmpty()) {
                logger.warn("没有找到符合条件的设备");
                
                // 如果没有找到设备，尝试返回所有设备（不过滤类型）
                SbEquipmentVo allQuery = new SbEquipmentVo();
                allQuery.setEquipmentStatus("0"); // 仍保持状态筛选
                List<SbEquipmentVo> allEquipments = equipmentService.selectSbEquipmentList(allQuery);
                logger.info("查询所有状态为0的设备: 找到{}台", allEquipments.size());
                
                // 如果有设备，记录它们的类型ID
                if (!allEquipments.isEmpty()) {
                    logger.info("所有可用设备的类型ID:");
                    for (SbEquipmentVo equipment : allEquipments) {
                        logger.info("设备ID: {}, 名称: {}, 类型ID: {}", 
                            equipment.getEquipmentId(), equipment.getEquipmentName(), equipment.getEquipmentTypeId());
                    }
                }
                
                // 返回正常查询结果（空列表）
                return AjaxResult.success(equipments);
            } else {
                for (SbEquipmentVo equipment : equipments) {
                    logger.info("设备ID: {}, 名称: {}, 编码: {}, 类型ID: {}", 
                        equipment.getEquipmentId(), equipment.getEquipmentName(), 
                        equipment.getEquipmentCode(), equipment.getEquipmentTypeId());
                }
            }
            
            return AjaxResult.success(equipments);
        } catch (Exception e) {
            logger.error("获取设备列表失败", e);
            return AjaxResult.error("获取设备列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有可用设备列表（不按类型过滤）
     */
    @GetMapping("/list/all")
    public AjaxResult getAllEquipments() {
        try {
            logger.info("获取所有可用设备列表");
            SbEquipmentVo query = new SbEquipmentVo();
            query.setEquipmentStatus("0"); // 假设0表示空闲状态
            
            List<SbEquipmentVo> equipments = equipmentService.selectSbEquipmentList(query);
            logger.info("查询到{}台设备", equipments.size());
            
            // 记录设备详情以便调试
            if (equipments.isEmpty()) {
                logger.warn("没有找到符合条件的设备");
            } else {
                logger.info("前5台设备信息:");
                for (int i = 0; i < Math.min(5, equipments.size()); i++) {
                    SbEquipmentVo equipment = equipments.get(i);
                    logger.info("设备ID: {}, 名称: {}, 编码: {}, 类型ID: {}", 
                        equipment.getEquipmentId(), equipment.getEquipmentName(), 
                        equipment.getEquipmentCode(), equipment.getEquipmentTypeId());
                }
            }
            
            return AjaxResult.success(equipments);
        } catch (Exception e) {
            logger.error("获取所有设备列表失败", e);
            return AjaxResult.error("获取所有设备列表失败：" + e.getMessage());
        }
    }
}
